//
//  CNM_APNS.swift
//  one_swift
//
//  Created by Mac mini on 2021/5/8.
//  用于注册远程通知

import UIKit
import UserNotifications // iOS10需要用到的推送框架


public protocol CNMApnsDelegate: AnyObject {
    @available(iOS 10.0, *)
    func cnm_apnsWillPresent(_ notification: UNNotification)
    @available(iOS 10.0, *)
    func cnm_apnsDidReceive(_ response: UNNotificationResponse)
}


public class CNMApns: NSObject {
    public static let shared = CNMApns()
    public weak var apnsDelegate: CNMApnsDelegate?
    
    public func registerAPNs(_ application: UIApplication) {
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            // 请求推送权限
            center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
                if (error != nil && granted) {
                    DispatchQueue.main.async {
                        application.registerForRemoteNotifications()
                    }
                    print("注册成功")
                } else {
                    print("注册失败")
                }
            }
            // 可以通过 getNotificationSettings 获取权限设置
            center.getNotificationSettings { (settings) in
                print("获取用户推送权限的settings", settings)
            }
        } else {
            let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        }
    }
}

@available(iOS 10.0, *)
extension CNMApns: UNUserNotificationCenterDelegate {
    /// iOS10新增：处理前台收到通知的代理方法
    public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // 收到的通知
        print(notification.request.content)
        
        self.apnsDelegate?.cnm_apnsWillPresent(notification)
        
        completionHandler([.alert, .sound, .badge])
    }
    
    /// iOS10新增：处理后台点击通知的代理方法
    public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 收到的通知
        let content: UNNotificationContent = response.notification.request.content
        
        let userInfo = content.userInfo
        // 通知时间
        let noticeDate = response.notification.date
        // 标题
        let title = content.title
        // 副标题
        let subtitle = content.subtitle
        // 内容
        let body = content.body
        // 角标
        let badge = content.badge ?? 0
        // 取得通知自定义字段内容，例：获取key为"Extras"的内容
        let extras = userInfo["Extras"]
        
        print("Notification, date: \(noticeDate), title: \(title), subtitle: \(subtitle), body: \(body), badge: \(badge), extras: \(String(describing: extras)).")
        
        self.apnsDelegate?.cnm_apnsDidReceive(response)
        
        completionHandler()
    }
}
